<template>
  <div>
    <h2>患者管理</h2>
    <div class="operatingBox">
      <div class="operating">
        <el-button type="success" icon="el-icon-plus" size="small" @click="addPatient">新增</el-button>
        <el-button type="primary" icon="el-icon-sort" size="small" @click="transferPa">转交</el-button>
        <el-button type="info" icon="el-icon-search" size="small" @click="dialogFormVisible2 = true">高级搜索</el-button>
        <download-excel style="display: inline-block; margin-left: 10px;" :data="tableData" :fields="json_fields"
          :header="headers" :name="name">
          <el-button type="success" icon="el-icon-upload" size="small">导出</el-button>
        </download-excel>

      </div>
      <div class="operating">
        <el-input placeholder="请输入患者名称" v-model="input1" class="input-with-select">

          <el-button slot="append" icon="el-icon-search" @click="searchPatients(input1)"></el-button>
        </el-input>
      </div>
    </div>

    <div class="tab-content">
      <el-table ref="multipleTable" v-loading="loading" :data="tableData" tooltip-effect="dark" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="50" align="center">
        </el-table-column>
        <!-- <el-table-column label="选择" width="55">

                  </el-table-column> -->
        <el-table-column prop="type" label="类型" width="100">
          <!-- <el-link type="info" style="text-decoration:none">信息链接</el-link> -->

          <template slot-scope="scope">
            <div v-if="scope.row.type == 0">私海</div>
            <div v-if="scope.row.type == 1">公海</div>
          </template>


        </el-table-column>
        <el-table-column prop="name" label="患者名称" width="120" align="center">
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.sex == 0">女</div>
            <div v-if="scope.row.sex == 1">男</div>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" align="center">
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="120" align="center">
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号码" width="180" align="center">
        </el-table-column>
        <el-table-column prop="medicareNum" label="医保卡号" width="150" align="center">
        </el-table-column>
        <el-table-column prop="province" label="省市" width="120" align="center">
        </el-table-column>
        <el-table-column prop="address" label="详细地址" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="userName" label="负责人" width="120" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" align="center">
        </el-table-column>
        <el-table-column prop="followCount" label="跟进" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="toFol(scope.row)">{{ scope.row.followCount }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="diagnosisCount" label="病例" width="120" align="center">
          <!-- v-for="item in this.tableData" -->
          <template slot-scope="scope">
            <el-button type="text" @click="toDia(scope.row)">{{ scope.row.diagnosisCount }}</el-button>
          </template>

        </el-table-column>
        <el-table-column prop="status" label="状态" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <el-tag disable-transitions type="success" v-if="scope.row.status == 0">有效</el-tag>
            <el-tag disable-transitions type="info" v-if="scope.row.status == 1">无效</el-tag>
            <!-- <el-tag disable-transitions type="success" v-if="scope.row.status == null">有效</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column fixed="right" prop="operation" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit-outline" size="mini"
              @click="editPatient(scope.$index, scope.row)">修改</el-button>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="makeBill(scope.$index, scope.row)" :disabled="scope.row.status == 1">开单</el-button>
            <el-button type="danger" icon="el-icon-close" size="mini"
              @click="delPa(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">

        <!-- 分页器 -->
        <Pagination :total="total" :pageSize="pageSize" @getPagination="getPagination"></Pagination>
      </div>

    </div>



    <!-- 转交dialog -->
    <el-dialog :visible.sync="dialogFormVisible" width="30%">
      <el-form> <!-- :model="form"-->
        <el-form-item>
          <span slot="label">
            <span class="labelText">部门</span>
          </span>
          <el-select v-model="depData.department" placeholder="--请选择部门--" style="width: 100%;">
            <el-option v-for="item in transferDep" :value="item.depId" :label="item.depName" :key="item.depId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item> <!-- :label-width="formLabelWidth"-->
          <span slot="label">
            <span class="labelText">人员</span>
          </span>
          <el-select v-model="depData.personId" style="width: 100%;" @focus="getDepartmentPer">
            <el-option v-for="item in personData" :value="item.id" :label="item.realName" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="transferForm">转交</el-button>
      </div>
    </el-dialog>

    <!-- --高级搜索dialog -->
    <el-dialog :visible.sync="dialogFormVisible2" width="40%">
      <el-form :model="searchForm" ref="searchForm" :rules="rules"> <!-- :model="form"-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item class="select">
              <span slot="label">
                <span class="labelText">类型</span>
              </span>
              <el-select v-model="searchForm.type" placeholder="--选择类型--" style="width: 100%">
                <el-option label="私海" value="0"></el-option>
                <el-option label="公海" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <span slot="label">
                <span class="labelText">患者</span>
              </span>
              <el-input v-model="searchForm.name" style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item>
              <span slot="label">
                <span class="labelText">身份证号</span>
              </span>

              <el-input v-model="searchForm.idCard" style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item prop="startTime">
              <span slot="label">
                <span class="labelText">时间起</span>
              </span>
              <!-- <el-date-picker v-model="searchForm.startTime" type="datetime" placeholder="选择日期时间" style="width: 100%">
              </el-date-picker> -->
              <el-input v-model="searchForm.startTime" type="datetime" style="width: 100%"></el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item>
              <span slot="label">
                <span class="labelText">状态</span>
              </span>
              <el-select v-model="searchForm.status" placeholder="--选择状态--" style="width: 100%">
                <el-option label="有效" value="0"></el-option>
                <el-option label="无效" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <span slot="label">
                <span class="labelText">手机</span>
              </span>
              <el-input v-model="searchForm.phone" style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item>
              <span slot="label">
                <span class="labelText">医保卡号</span>
              </span>
              <el-input v-model="searchForm.medicareNum" style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item prop="stopTime">
              <span slot="label">
                <span class="labelText">时间止</span>
              </span>

              <!-- <el-date-picker v-model="searchForm.stopTime" type="datetime" placeholder="选择日期时间" style="width: 100%">
              </el-date-picker> -->
              <el-input v-model="searchForm.stopTime" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="advancedSearchPa('searchForm')">搜索</el-button>
        <el-button @click="resetForm('searchForm')">重置</el-button>

      </div>
    </el-dialog>
  </div>
</template>
<script>

// import { getPatientsList } from '@/api/patient';
import Pagination from '@/components/Pagination'
import dayjs from 'dayjs';
import { mapMutations } from 'vuex'

export default {
  name: 'paManage',
  mixins: [],
  props: {

  },
  filters: {

  },
  data() {
    return {
      //

      //加载
      loading: true,

      //导出的表格数据
      // json_data:{

      // },

      //表头对应的数据属性
      json_fields: {
        "类型": "type",
        "患者名称": "name",
        "性别": "sex",
        "年龄": "age",
        "手机号码": "phone",
        "身份证号码": "idCard",
        "医保卡号": "medicareNum",
        "详细地址": "address",
        "负责人": "userName",
        "创建时间": "createTime",
        "病例": "diagnosisCount",
        "状态": "status",
      },
      //表格抬头的名字
      headers: "患者管理表格",
      //表格名称
      name: "患者管理列表",

      //转交dialog 是否打开
      dialogFormVisible: false,
      //转交提交数据 ---传参
      transferData: {
        "patientIds": [],
        "userId": 1
      },


      //dialog form表单数据内容
      depData: {
        department: "",//部门Id
        personId: "",//用户id
      },
      //部门信息
      transferDep: {
        depId: "",
        depName: "",
        depPho: "",
      },
      //部门人员信息
      personData: {},

      //高级搜索dialog
      dialogFormVisible2: false,
      searchForm: {
        "idCard": "",
        "medicareNum": "",
        "name": "",
        "phone": "",
        "startTime": "",
        "status": "",
        "stopTime": "",
        "type": "",
        "currentPage": "",
        "pageSize": "",
      },
      //规则
      rules: {
        // startTime: [{ required: true, message: '请输入日期', trigger: 'change' }],
        // stopTime: [{ required: true, message: '请输入日期', trigger: 'change' }]
      },


      //搜索框的内容
      input1: "",

      //表格数据
      tableData: [],


      //多选的值
      multipleSelection: [],
      patientsId: [],//多选的患者id数组

      //表格的内容量共有几条
      total: 0,
      currentPage: 1,
      pageSize: 10,


      //----页码判断----普搜的数据-----所有列表数据
      a: "",



    };
  },

  computed: {

  },
  components: {
    Pagination
  },
  created() {
    this.getAllPatientsList(this.currentPage, this.pageSize);
  },

  mounted() {

  },


  methods: {
    dayjs,
    //导入editPatient模块
    ...mapMutations("editPatient", ['changeTitle', 'changeRowData']),


    //获取页码
    getPagination(page) {
      // console.log("----", page);
      this.currentPage = page;
      this.searchForm.currentPage = page
      if (this.a == "所有") {
        this.getAllPatientsList(this.currentPage, this.pageSize)
      } else if (this.a == "普搜") {
        this.searchPatients(this.input1, this.currentPage, this.pageSize)
      } else if (this.a == "高级") {
        this.advancedSearchPa(this.searchForm)
      }

    },
    //获取患者列表
    async getAllPatientsList(currentPage, pageSize) {

      let res = await this.$api.patients.getPatientsList({ currentPage, pageSize })

      if (res.data.code === 200) {

        this.tableData = res.data.data.list;
        this.tableData.forEach((item) => {
          if (item.followCount == 0) {
            item.followCount = null
          }
          if (item.diagnosisCount == 0) {
            item.diagnosisCount = null
          }

        })
        //总数
        this.total = res.data.data.total;
        //加载loading
        this.loading = false

        //判断页面数据内容
        this.a = "所有"
      } else {
        console.log('请求失败');
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
        }, 1000)
        this.tableData = [];
        this.a = "";
        this.pageSize = 0;
        this.total = 1;
      }
    },
    // async getPatientCase(){},


    //多选框
    handleSelectionChange(val) {

      this.multipleSelection = val;
      this.transferData.patientIds = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        this.transferData.patientIds.push(Number(this.multipleSelection[i].id))
      }

    },


    //新增
    addPatient() {
      this.$router.push("/patient/addPatient")
    },

    //转交  获取部门 
    async transferPa() {
      this.depData.department = "";
      this.depData.personId = ""
      this.dialogFormVisible = true;
      let res = await this.$api.patients.getPaDepartment()
      console.log(res);
      if (res.data.code === 200) {
        this.transferDep = res.data.data
        // console.log( this.transferDep);
      }

    },
    //转交 获取部门人员
    async getDepartmentPer() {
      // console.log(this.depData.department);
      let depId = this.depData.department
      let res = await this.$api.patients.getDepartmentPerson(depId)
      // console.log(res);
      if (res.data.code === 200) {
        this.personData = res.data.data;
        //  console.log(this.ptransferDepersonData);
      }
    },
    //-----转交的提交功能
    async transferForm() {
      this.dialogFormVisible = false
      this.transferData.userId = this.depData.personId;//部门用户id
      // console.log(this.transferData);
      // console.log(this.transferData.patientIds);//患者id数组
      // console.log(this.transferData.userId);
      if (this.transferData.patientIds.length > 0) {
        let res = await this.$api.patients.transfer(this.transferData)
        console.log("11111", res);
        if (res.data.code === 200) {
          // console.log("------------");
          this.getAllPatientsList(this.currentPage, this.pageSize);
          this.$message({
            type: 'success',
            message: '转交成功!'
          });
        } else {
          this.$message.error('转交失败');
        }
      } else {
        this.$message.error('转交失败，必须选择患者');
      }
    },

    //高级搜索的提交  
    async advancedSearchPa(searchForm) {

      if (this.searchForm.type == '私海') {
        this.searchForm.type = 0
      } else if (this.searchForm.type == '公海') {
        this.searchForm.type = 1
      }

      if (this.searchForm.status == "有效") {
        // console.log("111111");
        this.searchForm.status = 0
      } else if (this.searchForm.status == "无效") {
        this.searchForm.status = 1
      }

      this.dialogFormVisible2 = false;
      this.searchForm.currentPage = this.currentPage;
      this.searchForm.pageSize = this.pageSize;
      searchForm = this.searchForm
      // this.searchForm.startTime=dayjs(this.searchForm.startTime).format("YYYY-MM-DD HH:mm:ss");
      // this.searchForm.stopTime=dayjs(this.searchForm.stopTime).format("YYYY-MM-DD HH:mm:ss")
      // console.log(this.searchForm);
      this.$api.patients.advancedSearch(this.searchForm)
        .then((res) => {
          if (res.data.code === 200) {
            //渲染表格内容
            // console.log(res.data.data);
            this.tableData = res.data.data.list
            // console.log(this.tableData);
            this.tableData.forEach((item) => {
              if (item.followCount == 0) {
                item.followCount = null
              }
              if (item.diagnosisCount == 0) {
                item.diagnosisCount = null
              }
              // console.log(item.diagnosisCount);
            })
            //总数
            this.total = res.data.data.total;

            this.a = "高级";
            // this.searchForm = {}
          } else {
            this.a = ""
            this.$message.error('搜索失败');
            // console.log("高级搜索出现错误");
          }
        }).catch(() => {
          this.$message.error('搜索失败');
        })




    },
    //重置按钮
    resetForm(searchForm) {
      //跳转到列表页面
      this.dialogFormVisible2 = false;
      this.$router.push('/patient/paManage');
      this.searchForm = {};
    },

    //搜索  
    async searchPatients(name, currentPage, pageSize) {
      name = this.input1;
      currentPage = this.currentPage;
      pageSize = this.pageSize
      let res = await this.$api.patients.searchPatient(name, currentPage, pageSize)
      if (res.data.code === 200) {
        console.log(res.data.data.list);
        this.tableData = res.data.data.list
        //总数
        this.total = res.data.data.total;
        this.a = "普搜"
      } else {
        this.a = "",
          this.tableData = [];
        this.pageSize = 0;
        this.total = 1;
      }


    },


    //修改
    editPatient(index, row) {
      console.log(index, row);
      this.changeRowData(row)
      this.$router.push("/patient/editPatient")
    },

    //开单
    makeBill(index, row) {
      console.log(index, row);
      this.changeTitle('开单');
      this.changeRowData(row)
      this.$router.push('/patient/makeBill')
    },

    // 单个删除 
    delPa(index, row) {
      this.$confirm('删除该记录不能恢复, 确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //执行删除步骤,后台查询数据库，发起请求
        this.$api.patients.deletePatient(row.id)
          .then((res) => {
            console.log("111111111", res.data.code);
            console.log("111111111", res.data.msg);
            if (res.data.code === 200) {
              this.getAllPatientsList(this.currentPage, this.pageSize);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }

            if (res.data.code === 10010) {
              // console.log("111111111");
              this.$message({
                type: 'warning',
                message: res.data.msg
              });
              // this.$message.error(res.data.msg);
            }
          })
          .catch(() => {
            this.$message.error('删除失败');
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    toFol(row) {
      this.$router.push('/patient/paFollow')
    },
    toDia(row) {
      this.$router.push('/diagnosis/diaManage')
    },
  },

  

};
</script>

<style lang="less" scoped>
h2 {
  margin: 15px;

}

.operatingBox {
  background-color: white;
  margin: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 3px solid #ccc;
  border-radius: 5px;
}

.operating {
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 10px;
  margin-right: 10px;
}

.el-input {
  width: 200px;
}

.select {
  display: flex;
  flex-direction: column;
}

.labelText {
  // text-align: left;
  float: left;
  font-size: 14px;
  font-weight: 600;
  color: black;
}


.el-form-item {
  display: flex;

  flex-direction: column;
}

.el-input {
  width: 250px;
}

.tab-content {
  margin: 10px;
}
</style>